// ignore: avoid_web_libraries_in_flutter
import 'dart:html' hide Platform;
import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

final APP_BASEURL =
    kDebugMode ? "http://127.0.0.1:8080" : "http://${window.location.host}";

class HoxinUtil {
  static DateUtil dateUtil = DateUtil();
  static TimerUtil timerUtil = TimerUtil();
  static String model =
      "${Platform.operatingSystem}:${Platform.operatingSystemVersion}";
  static Dio dio = Dio()
    ..interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        return handler.next(options);
      },
      onError: (e, handler) {
        if (e.response != null && e.response!.statusCode == 500) {
          Map<String, dynamic> errorMap =
              e.response!.data as Map<String, dynamic>;
          EasyLoading.showToast(errorMap["message"] as String);
        }
        return handler.next(e);
      },
      onResponse: (response, handler) {
        return handler.next(response);
      },
    ))
    ..interceptors.add(PrettyDioLogger())
    ..options.baseUrl = APP_BASEURL
    ..options.connectTimeout = const Duration(seconds: 10)
    ..options.receiveTimeout = const Duration(seconds: 10);
  static Future<Map<String, dynamic>> httpGet(
    String url,
    dynamic data,
  ) async {
    var result = await dio.request(url,
        queryParameters: data, options: Options(method: 'GET'));
    return result.data as Map<String, dynamic>;
  }

  static Future<Map<String, dynamic>> httpPost(
    String url,
    dynamic data,
  ) async {
    var result =
        await dio.request(url, data: data, options: Options(method: 'POST'));
    return result.data as Map<String, dynamic>;
  }

  static Future<Map<String, dynamic>> httpDelete(
    String url,
    dynamic data,
  ) async {
    var result =
        await dio.request(url, data: data, options: Options(method: 'DELETE'));
    return result.data as Map<String, dynamic>;
  }

  static Future<Map<String, dynamic>> httpPut(
    String url,
    dynamic data,
  ) async {
    var result =
        await dio.request(url, data: data, options: Options(method: 'PUT'));
    return result.data as Map<String, dynamic>;
  }

  static Future<Map<String, dynamic>> httpPatch(
    String url,
    dynamic data,
  ) async {
    var result =
        await dio.request(url, data: data, options: Options(method: 'PATCH'));
    return result.data as Map<String, dynamic>;
  }
}
